package dataBase;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class ConnectionManager {
	final static String DRIVER = "com.mysql.jdbc.Driver";
	final static String URL = "jdbc:mysql://localhost:3306/";
	final static String DB_NAME = "CodeSharingDB";
	final static String DB_USER = "root";
	final static String DB_PASSWORD = "skravi";
	
	static int openConnections = 10;
	static ConnectionManager instance = null;
	
	private ConnectionManager() throws ClassNotFoundException {
		// Load the SQL Driver class. 
		Class.forName(DRIVER);
	}
	
	static public ConnectionManager getInstance() throws ClassNotFoundException
	{
		if (instance == null)
			instance = new ConnectionManager();
		return instance;
	}
	
	public synchronized Connection getConnection() throws SQLException {
		if (openConnections > 0){
			openConnections--;
			return DriverManager.getConnection (URL+DB_NAME, DB_USER, DB_PASSWORD);			
		}
		return null;
	}
	
	/**
	 * 
	 * @param isolationLevel see sql connection help 
	 * @return
	 */
	public synchronized Statement getStatement(int isolationLevel){
		Statement stmt = null;
		try{
			Connection con = getConnection();
		if (con == null){
			return null;
		}
		con.setAutoCommit(false);
		con.setTransactionIsolation(isolationLevel);
		stmt = con.createStatement(); 
		}
		catch (SQLException e){
			return null;
		}
		return stmt; 
	}
	public synchronized boolean commitAndClose(Statement stmt){
		if (stmt == null){
			return false;
		}
		try {
			Connection con = stmt.getConnection();
			con.commit();
			stmt.close();
			con.close();
			openConnections++;
		} catch (SQLException e) {
			return false;
		}
		return true;
	}
	public synchronized boolean rollbackAndClose(Statement stmt){
		if (stmt == null){
			return false;
		}
		try {
			Connection con = stmt.getConnection();
			con.rollback();
			stmt.close();
			con.close();
			openConnections++;
		} catch (SQLException e) {
			return false;
		}
		return true;
	}
}
